package com.hongning.railway.ui.main.fragments.home;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.hongning.railway.BR;
import com.hongning.railway.R;
import com.hongning.railway.app.AppBaseFragment;
import com.hongning.railway.app.AppViewModelFactory;
import com.hongning.railway.app.Constant;
import com.hongning.railway.databinding.FragmentHomeBinding;
import com.hongning.railway.entity.LoginEntity;
import com.hongning.railway.util.Apputils;
import com.hongning.railway.util.RetrofitClient;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.zhouwei.mzbanner.MZBannerView;

import java.util.HashMap;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter;


public class HomeFragment extends BaseFragment<FragmentHomeBinding,HomeViewModel> {


    public static HomeFragment newInstance() {
        return new HomeFragment();
    }


    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_home;
    }

    @Override
    public HomeViewModel initViewModel() {
        AppViewModelFactory appViewModelFactory= AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, appViewModelFactory).get(HomeViewModel.class);
    }

    @Override
    public int initVariableId() {
        return BR.homeviewmodel;
    }

    @Override
    public void initData() {
        super.initData();
        //给RecyclerView添加Adpter，请使用自定义的Adapter继承BindingRecyclerViewAdapter，重写onBindBinding方法，里面有你要的Item对应的binding对象。
        // Adapter属于View层的东西, 不建议定义到ViewModel中绑定，以免内存泄漏
//        binding.setAdapter(new BindingRecyclerViewAdapter());
        //请求网络数据
        Apputils.setDefaultHeaderView(binding.trRefhreh);

        viewModel.getNewsByPage(1);
        viewModel.getCategoryData();
        viewModel.requestBannerData();
        binding.topBanner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {
                viewModel.bannnerClick(i);
            }
        });
        binding.topBanner.setIndicatorVisible(false);
        initWebSetting();
        binding.webContent.setWebViewClient(new WebViewClient(){
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Log.i("****",request.getUrl().toString());
                return false;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        LoginEntity loginEntity = Apputils.getLoginInfo();
        if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Constant.user_password))&&loginEntity!=null&&loginEntity.getToken()!=null&&!TextUtils.isEmpty(loginEntity.getToken()))
        {
            binding.webContent.loadUrl(RetrofitClient.baseUrl_1+"/nbfp/api/loginForGet?userName="+loginEntity.getUserName()+"&password="+SPUtils.getInstance().getString(Constant.user_password));
        }
    }

   public void  initWebSetting(){
        WebSettings webSetting = binding.webContent.getSettings();

        webSetting.setDatabaseEnabled(true);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setTextSize(WebSettings.TextSize.NORMAL);

        // ===设置JS可用
        webSetting.setJavaScriptEnabled(true);
        // JS打开窗口
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        // ===设置JS可用
        // 可以访问文件
        webSetting.setAllowFileAccess(true);
        // ===缩放可用
        webSetting.setSupportZoom(true);
        webSetting.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); //设置缩放功能   //能不能缩放 取决于网页设置
        webSetting.setLoadWithOverviewMode(false);
        webSetting.setBuiltInZoomControls(true);
        // ===缩放可用
        // 支持多窗口
        webSetting.setSupportMultipleWindows(true);
        // ===============缓存
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);// 决定是否从网络上取数据。
        webSetting.setAppCacheEnabled(true);
        // ===============缓存
        webSetting.setUseWideViewPort(false);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // ==定位
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);


    }

    @Override
    public void initViewObservable() {
        viewModel.uc.finishRefreshing.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                binding.trRefhreh.finishRefreshing();
                binding.trRefhreh.setEnableLoadmore(true);
//                binding.trRefhreh.setHeaderView();
            }
        });

        viewModel.uc.finishLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                binding.trRefhreh.finishLoadmore();
            }
        });

        viewModel.uc.enableLoadmore.observe(this, new Observer() {
            @Override
            public void onChanged(@Nullable Object o) {
                binding.trRefhreh.setEnableLoadmore(false);
            }
        });
    }
}
